<?php
/******************************************************************************
 *
 *    OpenZoowa - Web App to manage events
 *    Copyright (C) 2008 Jesus Ruiz-Ayucar
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as
 *    published by the Free Software Foundation, either version 3 of the
 *    License, or (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *****************************************************************************/
   require_once (modelspath.'event.php');
   class EventController {
      public function show() {
         if (isset($_GET['id'])) {
            require_once (modelspath.'comment.php');
            try {
               global $lang;
               $event = new Event($_GET['id']);
               $template = Util::startupTemplate('event','show');
               $template->assign('title', $lang['main_title']);
               $template->assign('event', $event);
               $regions = Region::getList(1);
               $template->assign('regions', $regions);
               $template->display('index.tpl');
            } catch (Exception $e) {
               echo '404';
            }
         } else {
            echo '404';
         }
      }

      private function buildPagination($url, $pages) {
         for($i = 1; $i <= $pages; $i++) {
            $result[$i] = $url.'page='.$i;
         }
         return $result;
      }

      public function index() {
         global $lang;
         $template = Util::startupTemplate('event','index');
         $template->assign('title', $lang['main_title']);
         $regions = Region::getList(1);
         $template->assign('regions', $regions);

         if(isset($_GET['page'])) {
            $page = $_GET['page'];
         } else {
            $page = 1;
         }

         $events = Event::getList($page-1);
         $template->assign('events', $events);
         $pages = $this->buildPagination('index.php?', Event::getList());
         $template->assign('pagination', $pages);
         $template->assign('page', $page);

         $template->display('index.tpl');
      }

      public function search() {
         global $lang;
         $template = Util::startupTemplate('event','search');
         $template->assign('title', $lang['main_title']);
         $regions = Region::getList(1);
         $template->assign('regions', $regions);

         if(isset($_GET['page'])) {
            $page = $_GET['page'];
         } else {
            $page = 1;
         }

         if(isset($_GET['when']) &&
            ($_GET['when'] == 'week' ||
            $_GET['when'] == 't_month' ||
            $_GET['when'] == 'n_month' ||
            $_GET['when'] == 'o_month'))
         {
            switch($_GET['when']) {
               case 'week':
                  $from = date('Y-m-d');
                  $to = date('Y-m-d', strtotime('next sunday'));
                  break;
               case 't_month':
                  $month = date('m');
                  $year = date('Y');
                  $from = date('Y-m-d');
                  $to = date('Y-m-'.Util::days_of_month($month, $year));
                  break;
               case 'n_month':
                  $next_month = strtotime('+1 month');
                  $year = date('Y', $next_month);
                  $month = date('m', $next_month);
                  $day = Util::days_of_month($month,$year);
                  $from = date('Y-m-01', $next_month);
                  $to = $year.'-'.$month.'-'.$day;
                  break;
               case 'o_month':
                  $from = date('Y-m-01', strtotime('+2 month'));
                  $to = date('Y-m-d', strtotime('+1 year +2 month'));
                  break;
            }
            $events = Event::getList($page-1,0,$from,$to);
            $pages = $this->buildPagination('index.php?c=event&amp;a=search&amp;when='.$_GET['when'].'&amp;',
               Event::getList(null,0,$from,$to));
         } elseif(isset($_GET['where'])) {
            $events = Event::getList($page-1, $_GET['where']);
            $pages = $this->buildPagination('index.php?c=event&amp;a=search&amp;where='.$_GET['where'].'&amp;',
               Event::getList(null,$_GET['where']));
         } elseif(isset($_GET['what'])) {
            $events = Event::search($page-1, $_GET['what']);
            $pages = $this->buildPagination('index.php?c=event&amp;a=search&amp;what='.$_GET['what'].'&amp;',
               Event::search(null,$_GET['what']));
         } else {
            die('404');
         }
         $template->assign('pagination', $pages);
         $template->assign('events', $events);
         $template->assign('page', $page);
         $template->display('index.tpl');
      }

      public function create() {
         global $lang, $current_user;
         if (!($current_user->getId() > 0)) {
            header('Location: /index.php?c=user&a=login');
            die;
         }

         $template = Util::startupTemplate('event','create');
         $template->assign('countries', Country::getList());
         $template->assign('categories', Category::getList());
         $template->assign('title', $lang['main_title']);
         $template->display('index.tpl');
      }

      public function add() {
         global $current_user;
         if (!($current_user->getId() > 0)) {
            header('Location: /index.php?c=user&a=login');
            die;
         }

         if ($_POST['aforo'] == 'limited') {
            // Limited
            $num_aforo = $_POST['num_aforo'];
         } elseif ($_POST['aforo'] == 'unlimited') {
            // Unlimited
            $num_aforo = -1;
         } else {
            // Unknown
            $num_aforo = 0;
         }

         $error = array();
         $event = new Event();
         Util::addErrorMsg($error, $event->setName($_POST['name']));
         Util::addErrorMsg($error, $event->setCategory($_POST['category']));
         Util::addErrorMsg($error, $event->setCost($_POST['cost']));
         Util::addErrorMsg($error, $event->setAforo($num_aforo));
         Util::addErrorMsg($error, $event->setDescription($_POST['description']));
         Util::addErrorMsg($error, $event->setTags($_POST['tags']));
         Util::addErrorMsg($error, $event->setPromoter($_POST['promoter']));
         Util::addErrorMsg($error, $event->setUser($_POST['user']));
         Util::addErrorMsg($error, $event->setDateStart(
            $_POST['date_start_Year'],
            $_POST['date_start_Month'],
            $_POST['date_start_Day']));
         if ($_POST['moreaday'] == 'yes') {
            Util::addErrorMsg($error, $event->setDateEnd(
               $_POST['date_end_Year'],
               $_POST['date_end_Month'],
               $_POST['date_end_Day']));
         }
         Util::addErrorMsg($error, $event->setDateDetails($_POST['date_details']));
         Util::addErrorMsg($error, $event->setTime($_POST['time']));
         Util::addErrorMsg($error, $event->setCity($_POST['city']));
         Util::addErrorMsg($error, $event->setAddress($_POST['address']));
         Util::addErrorMsg($error, $event->setPlace($_POST['place']));
         Util::addErrorMsg($error, $event->setUrl($_POST['url']));
         Util::addErrorMsg($error, $event->setPhone($_POST['phone']));
         Util::addErrorMsg($error, $event->setUser($current_user->getId()));

         if (!count($error)) {
            $id = $event->add();
            header('Location: /?c=event&a=show&id='.$id);
            die;
         } else {
            global $lang;
            $template = Util::startupTemplate('event','create');
            $template->assign('countries', Country::getList());
            $template->assign('categories', Category::getList());
            $template->assign('error', $error);
            $template->assign('title', $lang['main_title']);
            $template->assign('name', $_POST['name']);
            $template->assign('category', $_POST['category']);
            $template->assign('cost', $_POST['cost']);
            $template->assign('aforo', $_POST['aforo']);
            $template->assign('num_aforo', $_POST['num_aforo']);
            $template->assign('dontknow', $_POST['dontknow']);
            $template->assign('description', $_POST['description']);
            $template->assign('tags', $_POST['tags']);
            $template->assign('promoter', $_POST['promoter']);

            $date_start = mktime(0,0,0,$_POST['date_start_Month'],$_POST['date_start_Day'],$_POST['date_start_Year']);
            $date_end = mktime(0,0,0,$_POST['date_end_Month'],$_POST['date_end_Day'],$_POST['date_end_Year']);
            $template->assign('date_start', $date_start);
            $template->assign('date_end', $date_end);

            $template->assign('date_details', $_POST['date_details']);
            $template->assign('moreaday', $_POST['moreaday']);
            $template->assign('time', $_POST['time']);
            $template->assign('address', $_POST['address']);
            $template->assign('place', $_POST['place']);
            $template->assign('url', $_POST['url']);
            $template->assign('phone', $_POST['phone']);

            if (!empty($_POST['city'])) {
               $city = new City($_POST['city']);
               $regions = Region::getList($city->getRegion()->getCountry()->getId());
               $cities = City::getList($city->getRegion()->getId());
               $template->assign('regions', $regions);
               $template->assign('cities', $cities);
               $template->assign('country', $city->getRegion()->getCountry()->getId());
               $template->assign('region', $city->getRegion()->getId());
               $template->assign('city', $_POST['city']);
            }

            $template->display('index.tpl');
         }
      }

      public function edit() {
         global $lang, $current_user;
         if (!($current_user->getId() > 0)) {
            header('Location: /index.php?c=user&a=login');
            die;
         }

         try {
            $event = new Event($_GET['id']);
         } catch (Exception $e) {
            die('404');
         }

         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if ($_POST['aforo'] == 'limited') {
               // Limited
               $num_aforo = $_POST['num_aforo'];
            } elseif ($_POST['aforo'] == 'unlimited') {
               // Unlimited
               $num_aforo = -1;
            } else {
               // Unknown
               $num_aforo = 0;
            }

            $error = array();
            Util::addErrorMsg($error, $event->setName($_POST['name']));
            Util::addErrorMsg($error, $event->setCategory($_POST['category']));
            Util::addErrorMsg($error, $event->setCost($_POST['cost']));
            Util::addErrorMsg($error, $event->setAforo($num_aforo));
            Util::addErrorMsg($error, $event->setDescription($_POST['description']));
            Util::addErrorMsg($error, $event->setTags($_POST['tags']));
            Util::addErrorMsg($error, $event->setPromoter($_POST['promoter']));
            Util::addErrorMsg($error, $event->setUser($_POST['user']));
            Util::addErrorMsg($error, $event->setDateStart(
               $_POST['date_start_Year'],
               $_POST['date_start_Month'],
               $_POST['date_start_Day']));
            if ($_POST['moreaday'] == 'yes') {
               Util::addErrorMsg($error, $event->setDateEnd(
                  $_POST['date_end_Year'],
                  $_POST['date_end_Month'],
                  $_POST['date_end_Day']));
            }
            Util::addErrorMsg($error, $event->setDateDetails($_POST['date_details']));
            Util::addErrorMsg($error, $event->setTime($_POST['time']));
            Util::addErrorMsg($error, $event->setCity($_POST['city']));
            Util::addErrorMsg($error, $event->setAddress($_POST['address']));
            Util::addErrorMsg($error, $event->setPlace($_POST['place']));
            Util::addErrorMsg($error, $event->setUrl($_POST['url']));
            Util::addErrorMsg($error, $event->setPhone($_POST['phone']));
            Util::addErrorMsg($error, $event->setUser($current_user->getId()));

            if (!count($error)) {
               $event->update();
               header('Location: /?c=event&a=show&id='.$event->getId());
               die;
            } else {
               global $lang;
               $template = Util::startupTemplate('event','create');
               $template->assign('countries', Country::getList());
               $template->assign('categories', Category::getList());
               $template->assign('error', $error);
               $template->assign('title', $lang['main_title']);
               $template->assign('name', $_POST['name']);
               $template->assign('category', $_POST['category']);
               $template->assign('cost', $_POST['cost']);
               $template->assign('aforo', $_POST['aforo']);
               $template->assign('num_aforo', $_POST['num_aforo']);
               $template->assign('dontknow', $_POST['dontknow']);
               $template->assign('description', $_POST['description']);
               $template->assign('tags', $_POST['tags']);
               $template->assign('promoter', $_POST['promoter']);

               $date_start = mktime(0,0,0,$_POST['date_start_Month'],$_POST['date_start_Day'],$_POST['date_start_Year']);
               $date_end = mktime(0,0,0,$_POST['date_end_Month'],$_POST['date_end_Day'],$_POST['date_end_Year']);
               $template->assign('date_start', $date_start);
               $template->assign('date_end', $date_end);

               $template->assign('date_details', $_POST['date_details']);
               $template->assign('moreaday', $_POST['moreaday']);
               $template->assign('time', $_POST['time']);
               $template->assign('address', $_POST['address']);
               $template->assign('place', $_POST['place']);
               $template->assign('url', $_POST['url']);
               $template->assign('phone', $_POST['phone']);

               if (!empty($_POST['city'])) {
                  $city = new City($_POST['city']);
                  $regions = Region::getList($city->getRegion()->getCountry()->getId());
                  $cities = City::getList($city->getRegion()->getId());
                  $template->assign('regions', $regions);
                  $template->assign('cities', $cities);
                  $template->assign('country', $city->getRegion()->getCountry()->getId());
                  $template->assign('region', $city->getRegion()->getId());
                  $template->assign('city', $_POST['city']);
               }

               $template->display('index.tpl');
            }

         } else {
            $template = Util::startupTemplate('event','edit');
            $template->assign('id', $event->getId());
            $template->assign('countries', Country::getList());
            $template->assign('categories', Category::getList());
            $template->assign('error', $error);
            $template->assign('title', $lang['main_title']);
            $template->assign('name', $event->getName());
            $template->assign('category', $event->getCategory()->getId());
            $template->assign('cost', $event->getCost());
            switch($event->getAforo()) {
               case '-1': $aforo = 'unknown'; break;
               case '0':  $aforo = 'unlimited'; break;
               default:   $aforo = 'limited';
            }
            $template->assign('aforo', $aforo);
            $template->assign('num_aforo', $event->getAforo());
            $template->assign('description', $event->getDescription());
            $template->assign('tags', $event->getTags());
            $template->assign('promoter', $event->getPromoter());
            $template->assign('date_start', $event->getDateStartTimestamp());
            $template->assign('date_end', $event->getDateEndTimestamp());
            $template->assign('date_details', $event->getDateDetails());
            $moreaday = ($event->getDateStart() != $event->getDateEnd())?'yes':'no';
            $template->assign('moreaday', $moreaday);
            $template->assign('time', $event->getTime());
            $template->assign('address', $event->getTime());
            $template->assign('place', $event->getPlace());
            $template->assign('url', $event->getUrl());
            $template->assign('phone', $event->getPhone());

            $city_id = $event->getCity()->getId();
            if (!empty($city_id)) {
               $regions = Region::getList($event->getCity()->getRegion()->getCountry()->getId());
               $cities = City::getList($event->getCity()->getRegion()->getId());
               $template->assign('regions', $regions);
               $template->assign('cities', $cities);
               $template->assign('country', $event->getCity()->getRegion()->getCountry()->getId());
               $template->assign('region', $event->getCity()->getRegion()->getId());
               $template->assign('city', $event->getCity()->getId());
            }

            $template->display('index.tpl');
         }
      }

      public function abuse() {
         if (isset($_GET['id'])) {
            require_once (modelspath.'comment.php');
            try {
               global $lang, $db;
               $event = new Event($_GET['id']);

               $SQL = 'SELECT email FROM users WHERE level = "admin"';
               $to = implode(',', $db->get_col($SQL));
               $subject = '[Abuso] - '.$event->getName();
               $message  = 'Se ha marcado el evento "';
               $message .= $event->getName() . '" como inapropiado o abuso.' . "\n\n";
               $message .= 'Registro:'."\n";
               $message .= 'Evento: http://'.$GLOBALS['domain'].'/index.php?c=event&a=show&id=' . $event->getId() . "\n";
               $message .= 'IP: ' . $_SERVER['REMOTE_ADDR'] . "\n";
               $message .= 'Fecha: ' . date('d-m-Y') . "\n\n\n";
               $message = wordwrap($message, 70);
               $headers = 'From: noreply@' . $GLOBALS['domain']. "\n";
               mail($to, $subject, $message, $headers);

               $template = Util::startupTemplate('event','show');
               $template->assign('title', $lang['main_title']);
               $template->assign('event', $event);
               $regions = Region::getList(1);
               $template->assign('regions', $regions);
               $comments = Comment::getCommentsFromEventId($event->getId());
               $template->assign('comments', $comments);
               $template->assign('abuse', true);
               $template->display('index.tpl');
            } catch (Exception $e) {
               echo '404';
            }
         } else {
            echo '404';
         }
      }

      public function share() {
         if (isset($_GET['id'])) {
            require_once (modelspath.'comment.php');
            try {
               global $lang, $db;
               $event = new Event($_GET['id']);

               $SQL = 'SELECT email FROM users WHERE level = "admin"';
               $to = implode(',', $db->get_col($SQL));
               $subject = '[Abuso] - '.$event->getName();
               $message  = 'Se ha marcado el evento "';
               $message .= $event->getName() . '" como inapropiado o abuso.' . "\n\n";
               $message .= 'Registro:'."\n";
               $message .= 'Evento: http://'.$GLOBALS['domain'].'/index.php?c=event&a=show&id=' . $event->getId() . "\n";
               $message .= 'IP: ' . $_SERVER['REMOTE_ADDR'] . "\n";
               $message .= 'Fecha: ' . date('d-m-Y') . "\n\n\n";
               $message = wordwrap($message, 70);
               $headers = 'From: noreply@' . $GLOBALS['domain']. "\n";
               mail($to, $subject, $message, $headers);

               $template = Util::startupTemplate('event','show');
               $template->assign('title', $lang['main_title']);
               $template->assign('event', $event);
               $regions = Region::getList(1);
               $template->assign('regions', $regions);
               $comments = Comment::getCommentsFromEventId($event->getId());
               $template->assign('comments', $comments);
               $template->assign('abuse', true);
               $template->display('index.tpl');
            } catch (Exception $e) {
               echo '404';
            }
         } else {
            echo '404';
         }
      }

      public function commentAdd() {
         global $current_user;
         if (!($current_user->getId() > 0)) {
            header('Location: /index.php?c=user&a=login');
            die;
         }

         require_once (modelspath.'comment.php');
         $event = new Event($_GET['id']);
         if (isset($_GET['id']) && $event->getId() == $_GET['id']) {
            if (isset($_POST['comment']) && !empty($_POST['comment'])) {
               $comment = new Comment();
               $comment->setEvent($event->getId());
               $comment->setUser($current_user->getId());
               $comment->setText($_POST['comment']);
               $comment->add();
            }
            header('Location: /index.php?c=event&a=show&id='.$_GET['id']);
         } else {
            echo '404';
         }
      }

      public function commentdel() {
         global $current_user;
         if ($current_user->getLevel() != 'admin') {
            header('Location: /index.php?c=user&a=login');
            die;
         }

         require_once (modelspath.'comment.php');
         $comment = new Comment($_GET['id']);
         $event_id = $comment->getEvent()->getId();
         $comment->del();
         header('Location: /index.php?c=event&a=show&id='.$event_id);
      }

      public function commentedit() {
         global $current_user;
         if ($current_user->getLevel() != 'admin') {
            header('Location: /index.php?c=user&a=login');
            die;
         }

         require_once (modelspath.'comment.php');
         $template = Util::startupTemplate('event','commentedit');
         $comment = new Comment($_GET['id']);
         $template->assign('comment', $comment);
         $template->display('index.tpl');
      }

      public function commentupdate() {
         global $current_user;
         if ($current_user->getLevel() != 'admin') {
            header('Location: /index.php?c=user&a=login');
            die;
         }

         require_once (modelspath.'comment.php');
         $comment = new Comment($_GET['id']);
         $comment->setText($_POST['text']);
         $comment->update();
         header('Location: /index.php?c=event&a=show&id='.$comment->getEvent()->getId());
      }

      public function inforss() {
         $template = Util::startupTemplate('event','inforss');
         $template->assign('title', $lang['main_title']);
         // Obtenemos regiones de España
         $regions = Region::getList(1);
         $template->assign('regions', $regions);
         $template->display('index.tpl');
      }

      public function rss() {
         header('Content-Type: text/xml; charset=UTF-8');
         $title = 'Zoowa España';
         $link = 'http://' . $GLOBALS['domain'] . $GLOBALS['base_url'];
         $description = 'Últimos eventos en España';
         if (isset($_GET['region'])) {
            $events = Event::getList(0,$_GET['region']);
         } else {
            $events = Event::getList(0);
         }

         if(isset($events)) {
            $last = new Event($events[0]->getId());
            $lastDate = date('D, j M Y H:i:s', $last->getDatePostTimestamp()) . ' GMT';
         }

         $dom = new DOMDocument('1.0');
         $node = $dom->createElement('rss');
         $rssnode = $dom->appendChild($node);
         $rssnode->setAttribute('version','2.0');
         $rssnode->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom');
         $node = $dom->createElement('channel');
         $channelnode = $rssnode->appendChild($node);
         $node = $dom->createElement('title', $title);
         $channelnode->appendChild($node);
         $node = $dom->createElement('link', $link);
         $channelnode->appendChild($node);
         $node = $dom->createElement('description', $description);
         $channelnode->appendChild($node);
         $node = $dom->createElement('language', 'es-ES');
         $channelnode->appendChild($node);

         if(isset($events)) {
            $node = $dom->createElement('lastBuildDate', $lastDate);
            $channelnode->appendChild($node);
         }

         if (isset($events)) {
            foreach($events as $event) {
               $node = $dom->createElement('item');
               $itemnode = $channelnode->appendChild($node);

               $node = $dom->createElement('title', $event->getName());
               $itemnode->appendChild($node);

               $node = $dom->createElement('link', 'http://' . $GLOBALS['domain'] . $GLOBALS['base_url'] . 'index.php&amp;c=event&amp;a=show&amp;id=' . $event->getId());
               $itemnode->appendChild($node);

               $node = $dom->createElement('guid', 'http://' . $GLOBALS['domain'] . $GLOBALS['base_url'] . 'index.php&amp;c=event&amp;a=show&amp;id=' . $event->getId());
               $itemnode->appendChild($node);

               $node = $dom->createElement('description', $event->getDescription());
               $itemnode->appendChild($node);

               $node = $dom->createElement('pubDate', date('D, j M Y H:i:s', $event->getDatePostTimestamp()) . ' GMT');
               $itemnode->appendChild($node);
            }
         }
         $node = $dom->createElement("atom:link");
         $atom = $channelnode->appendChild($node);
         $atom->setAttribute('href', 'http://'.$GLOBALS['domain'].$GLOBALS['base_url'].'index.php?c=event&a=rss');
         $atom->setAttribute('rel', 'self');
         $atom->setAttribute('type', 'application/rss+xml');

         echo $dom->saveXML();
      }
   }
?>